package servlet;

import entity.Emp;
import util.ParameterUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 石小俊
 * @date 2023年10月20日 15:49
 */
@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        switch (path) {
            case "/add.emp":
                addEmp(request, response);
                break;
            case "/findAll.emp":
                findAll(request, response);
                break;
            case "/findById.emp":
                findById(request, response);
                break;
            case "/delete.emp":
                deleteById(request, response);
                break;
            case "/modify.emp":
                modifyEmp(request, response);
                break;
            default:
                PrintWriter out = response.getWriter();
                out.println("<h1 style='color:red;'>您输入的请求不存在,请检查请求是否正确!</h1>");
                break;
        }
    }

    protected void addEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        System.out.println("name:" + name + ",salary:" + salary + ",gender:" + gender + ",edu:" + edu + ",hobbies:" + Arrays.toString(hobbies));

        // 使用JDBC将数据添加到对应的数据库表中
        Connection conn = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");

            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_emp")
                    .append("   (name,salary,gender,edu,hobbies)")
                    .append(" values ")
                    .append("   (?,?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, ParameterUtil.arrayToString(hobbies));
            ps.executeUpdate();
            response.sendRedirect("findAll.emp");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("empMsg","服务器内部异常");
            request.getRequestDispatcher("/ems/addEmp.jsp").forward(request,response);
        }
    }

    protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        List<Emp> emps = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,name,salary ")
                    .append(" from t_emp ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()) {
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emps.add(emp);
            }
            // request.setAttribute(String key,Object value):向请求中存储数据,存储的数据可以是任意类型
            // request.getAttribute(key):从请求中取出数据
                // 只要是同一个请求都可以获取到对应数据
            request.setAttribute("emps",emps);
            // 跳转到对应JSP页面
            // 此处通过转发跳转到对应的员工列表的JSP页面,转发是共享请求的
            // 由于转发只能在服务器内部转移,因此对于转发其绝对路径的/表示的是应用名后面的/
            // 除了转发以外所有绝对路径的/都表示端口号后面的/
            request.getRequestDispatcher("/ems/empList.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    protected void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        Emp emp = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()) {
                emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setGender(rs.getString("gender"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
                request.setAttribute("emp",emp);
                request.getRequestDispatcher("/ems/modifyEmp.jsp").forward(request,response);
                return;
            }
            request.setAttribute("empMsg","未找到数据");
            request.getRequestDispatcher("/ems/empList.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("empMsg","服务器内部异常");
            request.getRequestDispatcher("/ems/empList.jsp").forward(request,response);
        }
    }

    protected void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取到请求中传递过来的需要删除的数据的主键id值
        String id = request.getParameter("id");

        Connection conn = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" delete from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            ps.executeUpdate();

            response.sendRedirect(request.getContextPath()+"/findAll.emp");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("empMsg","服务器内部异常");
            request.getRequestDispatcher("/findAll.emp").forward(request,response);
        }
    }

    protected void modifyEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");

        Connection conn = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append("   name = ?, ")
                    .append("   salary = ?, ")
                    .append("   gender = ?, ")
                    .append("   edu = ?, ")
                    .append("   hobbies = ? ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, ParameterUtil.arrayToString(hobbies));
            ps.setInt(6,Integer.parseInt(id));
            ps.executeUpdate();

            response.sendRedirect(request.getContextPath()+"/findAll.emp");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("empMsg","服务器内部异常");
            request.getRequestDispatcher("/ems/modifyEmp.jsp").forward(request,response);
        }
    }
}
